package Servelts;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import daoFactory.DaoFactory;
import sun.misc.BASE64Encoder;
import vo.Images;

import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;

public class UploadServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String status = request.getParameter("status");
		String url = "error.jsp";
		if(status.equals("uploadjsp")){
			String src = DaoFactory.getGoodFactory().get("4").getGsrc();
			request.setAttribute("src", src);
			url = "uploadImage.jsp";
		}
		if(status.equals("upload")){
				PrintWriter writer = response.getWriter();
				//创建DiskFileItemFactory 工厂类
				DiskFileItemFactory factory = new DiskFileItemFactory();
				//通过工厂类，创建ServletFileUpload
				ServletFileUpload upload = new ServletFileUpload(factory);
				//设置单个文件上传上限为：10m
				upload.setFileSizeMax(1024*1024*10);
				//设置总文件上传上限为：10m
				upload.setSizeMax(1024*1024*10);
				//获取上传文件的真实路径（服务器根目录的upload）
				String realPath = getServletContext().getRealPath("/Resources/images");
				try {
					//通过ServletFileUpload中的parseRequest()方法，将表单项解析为List<FileItem>
					List<FileItem> list = upload.parseRequest(request);
		//				System.out.println("表单项提交数量："+list.size());
					//迭代集合，查找文件元素（FileItem中的isFormField()==false）
					for (FileItem fileItem : list) {
		//					System.out.println("!!"+fileItem.getSize());
						if(fileItem.getSize()>0) {
							if(fileItem.isFormField() == false) {
								//时间戳命名
								String fName = System.currentTimeMillis() + ".jpg";
								//创建File为，上传文件预留位置（真实路径(D:dd/)+文件名）
								File file = new File(realPath+"/"+fName);
								if(!file.exists()){
									file.getParentFile().mkdir();
								}
								//文件表单项，write()，将文件上传到服务器
								fileItem.write(file);
								
								//相对路径
								String src = "Resources/images/" + fName;
								request.setAttribute("src", src);
								Images image = new Images();
								image.setSrc(src);
								
								url = "showimage.jsp";
							}else {
								//普通表单项
							}
						}
					}
				}catch (FileSizeLimitExceededException e) {
					writer.write("上传失败，单个文件上传大小不能超过1k!");
					System.out.println(e.getMessage());
				}catch (SizeLimitExceededException e) {
					System.out.println(e.getMessage());
					writer.write("上传失败，总文件上传大小不能超过2k!");
				}catch (Exception e) {
					System.out.println(e.getMessage());
			}
		}
		
		if(status.equals("download")){

			
			//1.通过文件名，获取文件真实路径。
			String fname = request.getParameter("fname");
			fname = fname.split("/")[2];
			String realPath = getServletContext().getRealPath("/Resources/images/"+fname);
			System.out.println("realPath:"+realPath);
			
			//2. 创建FileInputStream输入流，读入文件。
			FileInputStream fis = new FileInputStream(realPath);
			//3.创建输出流（response），响应给浏览器，实现文件下载功能。
			OutputStream ops = response.getOutputStream();
			//设置浏览器响应体文件类型
			String mimeType = request.getServletContext().getMimeType(fname);
			response.setContentType(mimeType);
			
			//解决文件名中文乱码问题
			String header = request.getHeader("User-Agent");
			if(header != null && header.contains("Firefox")) {
				fname = "=?utf-8?B?"+new BASE64Encoder().encode(fname.getBytes("utf-8"))+"?=";
			}else {
				fname = URLEncoder.encode(fname, "UTF-8");
			}
			
			//设置响应头
			response.setHeader("Content-Disposition", "attachment; filename="+fname);
			//边读边写
			byte[] b = new byte[1024];
			int len = 0;
			while((len = fis.read(b))!=-1) {
				ops.write(b, 0, len);
			}
			
			//关闭流
			fis.close();
			ops.flush();
			ops.close();
			url = "showimages.jsp";
		}
		
		request.getRequestDispatcher(url).forward(request, response);
		
	}
	
}
